package com.youlu.campus.component;

import com.youlu.campus.common.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 工具Utils
 */
@Slf4j
@Component
public class CommonUtils {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 生成订单编号
     */
    public String generateIncreNo(String key, Long expireTime, TimeUnit timeUnit) {
        log.info(":>>> 开始生成编号");
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        Long increment = entityIdCounter.getAndIncrement();
        log.info(":>>> 自增的长度为:{}", increment);
        if ((null == increment || increment.longValue() == 0)) {
            //初始设置过期时间
            entityIdCounter.expire(expireTime, timeUnit);
        }
        String no =
                TimeUtils.formatDate(new Date(), "yyyyMMddHHmmssSSS") + (long) (Math.random() * (1000)) + "-" + entityIdCounter;
        log.info(":>>> 生成的编号为:{},{}", key, no);
        return no;
    }
}
